# !/usr/bin/env python
# -*- coding: utf-8 -*-
from django.http import JsonResponse

from mytest import models
from mytest.utils.forms import *


class ComCrud(object):
    def get_add(self, request, model_name):

        # data = request.POST     # 可有可无，因为不写默认是无法识别被引用的，就写吧

        form = eval(f"{model_name}ModelForm(data=request.POST)")

        if form.is_valid():
            # form.cleaned_data 验证通过的数据，
            form.save()
            result = {
                "status": True,
            }
            return JsonResponse(result)

        # print("错误返回")
        return JsonResponse({"status": False, "error": form.errors})

    def get_list(self, request):
        pass

    def get_edit(self, request, model_name):
        uid = request.GET.get("uid")

        # 获取模型类
        my_class = model_name

        # 获取方法对象并执行
        # models.Admin.objects.filter()

        row_dict = eval(f"models.{my_class}.objects.filter(id={uid}).values().first()")
        # row_dict = models.PrettyNum.objects.filter(id=uid).values().first()   # 原版。
        row_object = eval(f"models.{my_class}.objects.filter(id={uid})")
        # row_object = models.PrettyNum.objects.filter(id=uid).first()

        if not row_dict:
            result = {
                "status": False,
                "tips": "编辑失败，数据ID不存在"
            }
            return JsonResponse(result)

        if request.method == "GET":
            result = {
                "status": True,
                "data": {
                    "rows": row_dict
                }
            }
            return JsonResponse(result)

        # row_object = getattr(models, f"{my_class}.objects.filter")(id=uid).first()
        # form = PrettyNumModelForm(data=request.POST, instance=row_object)
        form = eval(f"{my_class}ModelForm")(data=request.POST, instance=row_object)

        # 校验数据，正确则保存到数据库中。并返回状态True。
        if form.is_valid():
            form.save()
            return JsonResponse({
                "status": True
            })
        else:
            # 校验失败，返回False，并给出错误提示。
            return JsonResponse({
                "status": False,
                "error": form.errors
            })

    def get_delete(self, request, model_name):
        # 因为删除我只用了post请求，这里就不写get了
        uid = request.POST.get("uid")

        # 找到指定id的数据对象，执行删除命令
        # models.PrettyNum.objects.filter(id=uid).delete()
        eval(f"models.{model_name}.objects.filter(id=uid).delete()")

        print("看是否到删除")

        return JsonResponse({"status": True})
